
local easyNPCSearch = {}
_G["easyNPCSearch"] = easyNPCSearch

local ADDON = "easyNPCSearch"
local VERSION = "1.0"
local AUTHOR = "NashaRiochtDE"

function easyNPCSearch_OnLoad(this)
	this:RegisterEvent("LOADING_END")
end

function easyNPCSearch_OnEvent(event)

	if event == "LOADING_END" then
		
		function NpcTrackFrame_InitializeNpcList(NpcID)
			local count = 0
			if NpcID then
				count = NpcTrack_SearchNpcByDBID(NpcID)
			elseif NpcTrackFrame.TabID == 1 then
				local searcName = NpcTrackSearchEditBox:GetText()
				
				local word = {}
				local counter = 1				
				for w in string.gmatch(searcName, "%a+") do
					word[counter] = w
					counter = counter + 1
				end
				
				for k, v in ipairs(word) do
					local firstChar = string.sub(v, 1, 1)
					local restString = string.sub(v, 2)
					firstChar = string.upper(firstChar)
					restString = string.lower(restString)
					word[k] = firstChar..restString
				end
				
				local modTxt = ""
				for k = 1, #word, 1 do
					if k == #word then
						modTxt = modTxt..word[k]
					else
						modTxt = modTxt..word[k].." "
					end
				end
				
				searcName = modTxt

				count = NpcTrack_SearchNpc(searcName)
			elseif NpcTrackFrame.TabID == 2 then
				local bIgnoreLV = not QuestNpcTrackSearchCheckButtonHideLow:IsChecked()
				local bSameZone = QuestNpcTrackSearchCheckButtonSameZone:IsChecked()
				count = NpcTrack_SearchQuestNpc(bIgnoreLV , bSameZone)
			end
			g_NpcTrackSearchResultTable = {}
			g_NpcTrackSearchResultListSelected = -1
			local npcID, name, x, z
			for i=1 , count do
				npcID, name, mapID, x, z = NpcTrack_GetNpc(i)
				g_NpcTrackSearchResultTable[i] = {}
				g_NpcTrackSearchResultTable[i].npcID = npcID
				g_NpcTrackSearchResultTable[i].name = name
				g_NpcTrackSearchResultTable[i].mapID = mapID
				g_NpcTrackSearchResultTable[i].x = x
				g_NpcTrackSearchResultTable[i].z = z
			end
			if NpcID and count > 0 then
				g_NpcTrackSearchResultListSelected = 1
				NpcTrackFrame_TrackPreview(g_NpcTrackSearchResultTable[1])
			else
				g_NpcTrackSearchResultListSelected = nil
				NpcTrackFrame_TrackPreview(nil)
			end	
			if count > DF_NPCTRACKFRAME_SEARCHRESULTLIST_MAX then
				NpcTrackSearchResultListScrollBar:SetMaxValue(count - DF_NPCTRACKFRAME_SEARCHRESULTLIST_MAX)
			else
				NpcTrackSearchResultListScrollBar:SetMaxValue(0)
			end
			NpcTrackSearchResultListScrollBar_OnValueChanged(NpcTrackSearchResultListScrollBar, 0)
		end

	end
end
